﻿using System;
using System.Collections.Generic;
using Fuse8.DomainFramework.BusinessService;
using Fuse8.DomainFramework.Common.Locator;
using Fuse8.DomainFramework.Domain;
using Fuse8.DomainFramework.Practices.Domain.Interfaces;

namespace Fuse8.DomainFramework.Practices.BusinessService.Extensions
{
	public static class BusinessServiceExtensions
	{
		public static IEnumerable<TDomain> Find<TDomain, TParameter, TKey>(this IEntityBusinessService<TDomain, TKey> service, TParameter parameter)
			where TParameter : ICommandParameter
			where TDomain : class, IEntityObject<TKey>, new() where TKey : IComparable<TKey>, IEquatable<TKey>
		{
			return service.Find(GetCommand<TDomain, TParameter, TKey>(parameter));
		}

        public static TDomain FindOne<TDomain, TParameter, TKey>(this IEntityBusinessService<TDomain, TKey> service, TParameter parameter)
			where TParameter : ICommandParameter
            where TDomain : class, IEntityObject<TKey>, new() where TKey : IComparable<TKey>, IEquatable<TKey>
        {
			return service.FindOne(GetCommand<TDomain, TParameter, TKey>(parameter));
		}

		public static void Execute<TDomain, TParameter, TKey>(this IEntityBusinessService<TDomain, TKey> service, TParameter parameter)
			where TParameter : ICommandParameter
			where TDomain : class, IEntityObject<TKey>, new() where TKey : IComparable<TKey>, IEquatable<TKey>
		{
			service.Find(GetCommand<TDomain, TParameter, TKey>(parameter), true);
		}

		private static IEntityCommand<TDomain> GetCommand<TDomain, TParameter, TKey>(TParameter parameter)
			where TParameter : ICommandParameter
			where TDomain : class, IEntityObject<TKey>, new() where TKey : IComparable<TKey>, IEquatable<TKey>
		{
			var command = DependencyServiceLocator.Current.GetInstance<IEntityDataCommand<TDomain, TParameter, TKey>>();
			command.Parameter = parameter;
			return command;
		}
	}

}